package com.library.uiframework.activity;

import java.util.concurrent.TimeUnit;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import com.ali.music.navigator.backstack.AbstractActivity;
import com.bumptech.glide.Glide;
import com.library.uiframework.R;
import com.library.uiframework.mvp.IPageLifecycle;
import com.library.uiframework.mvp.PageLifecycleHelper;
import com.library.uiframework.utils.DisplayUtils;
import com.library.uiframework.utils.SDKVersionUtils;

/**
 * BaseActivity.java
 * Created by james on 2015/9/25 09:55.
 * Copyright (c) 2015 james. All rights reserved.
 *
 * @author james.guo
 * @version 1.0.0
 */
public class BaseActivity extends AbstractActivity {
    private static final String TAG = "ThemeActivityDemo";

    private View mBusinessView;

    private boolean mImmersiveObserverViewCreated = false;

    protected PageLifecycleHelper mPageLifecycleHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.instance().onCreate(this);

        //透明状态栏
        if (needTranslucentStatusBar() && SDKVersionUtils.hasKitKat()) {
            Window window = getWindow();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                        | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                window.getDecorView().setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                //不改变statusbar的颜色
//                window.setStatusBarColor(Color.TRANSPARENT);
                window.setNavigationBarColor(Color.TRANSPARENT);
            } else {
                //不改变statusbar的颜色
//                window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
            mPageLifecycleHelper = new PageLifecycleHelper();
        }

    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        registerPageLifecycles();
        mPageLifecycleHelper.onCreate();
    }

    final public void registerPageLifecycle(IPageLifecycle lifecycle) {
        mPageLifecycleHelper.register(lifecycle);
    }

    protected void registerPageLifecycles() {
    }

    protected boolean needTranslucentStatusBar() {
        return true;
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        initImmersiveViewObserver();
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        initImmersiveViewObserver();
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        initImmersiveViewObserver();
    }

    @Override
    public void addContentView(View view, ViewGroup.LayoutParams params) {
        if (!mImmersiveObserverViewCreated) {
            initImmersiveViewObserver();
        }
        super.addContentView(view, params);
    }

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    private void initImmersiveViewObserver() {
        mImmersiveObserverViewCreated = true;
        if (SDKVersionUtils.hasKitKat()) {
            View view = new View(this);
            view.setVisibility(View.INVISIBLE);
            view.setId(R.id.view_immersive_observer);
            view.setFitsSystemWindows(true);
            addContentView(view, new ViewGroup.LayoutParams(0, 0));
            onImmersiveViewObserverCreated(view);
        }
    }

    protected void onImmersiveViewObserverCreated(View observerView) {

    }

    /**
     * 设置一个放业务主体内容的view,用来统一处理背景等
     *
     * @param businessView businessView
     */
    protected void setBusinessView(View businessView) {
        mBusinessView = businessView;
    }

    @Override
    protected void onStart() {
        super.onStart();
        mPageLifecycleHelper.onStart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mPageLifecycleHelper.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActivityManager.instance().onResume(this);
        mPageLifecycleHelper.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActivityManager.instance().onPause(this);
        mPageLifecycleHelper.onPause();
    }


    protected void setFullscreen(boolean fullscreen) {
        Window window = getWindow();
        WindowManager.LayoutParams winParams = window.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        if (fullscreen) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        window.setAttributes(winParams);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mPageLifecycleHelper.onDestroy();
        setViewBackgroundDrawable(mBusinessView != null ? mBusinessView : getWindow().getDecorView(), null);
        mBusinessView = null;
    }

    /**
     * 设置一个背景图,为节省内存,此图应该各UI页面共用
     *
     * @param drawable 背景大图
     */
    public void setBackgroundDrawable(Drawable drawable) {
        setViewBackgroundDrawable(mBusinessView != null ? mBusinessView : getWindow().getDecorView(), drawable);
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void setViewBackgroundDrawable(View view, Drawable drawable) {
        if (view != null) {
            if (SDKVersionUtils.hasJellyBean()) {
                view.setBackground(drawable);
            } else {
                view.setBackgroundDrawable(drawable);
            }
        }
    }

    @Override
    public void finish() {
        super.finish();
    }

    private float mTouchDownX;
    private float mTouchDownY;
    private boolean mMoveAction;
    private long mLastClickTime;
    private boolean mAllowFastClickTemporarily;
    private static final int ACTION_MOVE_GAP_PX = DisplayUtils.dp2px(12);
    /**
     * 默认快速点击阙值
     */
    public static final long DEFAULT_FAST_CLICK_THRESHOLD = 500;

    private long mFastClickThreshold = TimeUnit.MILLISECONDS.toNanos(DEFAULT_FAST_CLICK_THRESHOLD);

    /**
     * @return 获取当前快速点击阙值, 单位毫秒
     */
    public long getFastClickThreshold() {
        return TimeUnit.NANOSECONDS.toMillis(mFastClickThreshold);
    }

    /**
     * @param fastClickThreshold 快速点击阙值,单位毫秒
     */
    public void setFastClickThreshold(long fastClickThreshold) {
        mFastClickThreshold = TimeUnit.MILLISECONDS.toNanos(fastClickThreshold);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mTouchDownX = ev.getX();
                mTouchDownY = ev.getY();
                mMoveAction = false;
                break;
            case MotionEvent.ACTION_MOVE:
                mMoveAction = mMoveAction || isMoveAction(ev);
                break;
            case MotionEvent.ACTION_UP:
                if (!mAllowFastClickTemporarily && !mMoveAction && isClickTooFast()) {
                    ev.setAction(MotionEvent.ACTION_CANCEL);
                }
                mAllowFastClickTemporarily = false;
                break;
            default:
                break;
        }
        try {
            return super.dispatchTouchEvent(ev);
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取快速点击支持
     */
    public void acquireFastClickSupport() {
        mAllowFastClickTemporarily = true;
    }

    private boolean isMoveAction(MotionEvent ev) {
        return (Math.abs(ev.getX() - mTouchDownX) > ACTION_MOVE_GAP_PX || Math.abs(ev.getY() - mTouchDownY) > ACTION_MOVE_GAP_PX);
    }

    private boolean isClickTooFast() {
        long time = System.nanoTime();
        if (time - mLastClickTime < mFastClickThreshold) {
            return true;
        }
        mLastClickTime = time;
        return false;
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        Glide.with(this).onTrimMemory(level);
    }
}
